package com.gakj.truck.third.api.service;

import com.alibaba.fastjson.JSONArray;
import com.alibaba.fastjson.JSONObject;
import com.gakj.truck.third.api.mapper.PurchaseTruckMapper;
import com.gakj.truck.third.api.mapper.TruckBrandMapper;
import com.gakj.truck.third.api.mapper.TruckInquiryMapper;
import com.gakj.truck.third.api.mapper.TruckModelMapper;
import com.gakj.truck.third.api.ouman.OumanService;
import com.gakj.truck.third.core.domain.PurchaseTruck;
import com.gakj.truck.third.core.domain.TruckBrand;
import com.gakj.truck.third.core.domain.TruckInquiry;
import com.gakj.truck.third.core.domain.TruckModel;
import com.gakj.truck.third.core.domain.area.ShtCity;
import com.gakj.truck.third.core.domain.area.ShtDistrict;
import com.gakj.truck.third.core.domain.area.ShtProvince;
import com.gakj.truck.third.core.enums.EnumPlatform;
import com.gakj.truck.third.core.utils.DateUtil;
import com.gakj.truck.third.core.utils.RequestUtils;
import org.springframework.beans.BeanUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.util.StringUtils;

import java.util.ArrayList;
import java.util.Date;
import java.util.List;

/**
 * 第三方求购相关操作
 * Created by gc on 2016/5/13.
 */
@Service
public class TruckInquiryService {

    private static final int HAS_SAVE = 1;
    private static final int NOT_SAVE = 0;
    @Autowired
    TruckInquiryMapper truckInquiryMapper;

    @Autowired
    OumanService oumanService;

    @Autowired
    PurchaseTruckMapper purchaseTruckMapper;

    @Autowired
    TruckBrandMapper brandMapper;

    @Autowired
    TruckModelMapper modelMapper;

    @Autowired
    AreaService areaService;

    public JSONObject save(TruckInquiry inquiry) {

        Long inline = truckInquiryMapper.save(inquiry);


        return RequestUtils.success(null);
    }


    public JSONObject update(TruckInquiry inquiry) {

        inquiry.setUpdatetime(new Date());

        truckInquiryMapper.update(inquiry);

        return RequestUtils.success(null);

    }

    public TruckInquiry getByOumanid(String truckId) {
        return truckInquiryMapper.getByOumanid(truckId);
    }


    public JSONObject saveOrUpdate(String jsondata) {
        JSONObject result = new JSONObject();

        JSONObject jsonObject = JSONObject.parseObject(jsondata);
        TruckInquiry inquiry = dealJSONObject(jsonObject);
        try {
            save(inquiry);
            result.put("resMsg", "保存成功!");
            result.put("resCode", "1");
        } catch (Exception ex) {
            ex.printStackTrace();
            result.put("resMsg", "保存失败!" + ex.getMessage());
            result.put("resCode", "0");
        }
        return result;
    }

    public JSONObject getInquiryTruckFromOuman(int day) {
        JSONObject json = oumanService.getTruckInquiryList(day);
        JSONObject result = new JSONObject();
        List<TruckInquiry> inquiries = new ArrayList<>();

        if (json != null && json.size() > 0) {
            JSONArray data = json.getJSONArray("data");
            if (data != null && data.size() > 0) {
                for (Object aData : data) {
                    JSONObject jsonObject = (JSONObject) aData;
                    TruckInquiry inquiry = dealJSONObject(jsonObject);
                    inquiry.setCreatetime(new Date());
                    inquiry.setUpdatetime(new Date());
                    inquiry.setSource("0");
                    inquiries.add(inquiry);
                }
            }
        }
        if (inquiries.size() > 0) {
            try {

                for (TruckInquiry inquiry : inquiries) {
                    TruckInquiry truckInquiry = this.getByOumanid(inquiry.getTruckId());
                    if (truckInquiry != null) {
                        //属性复制
                        inquiry = copyProperties(inquiry,truckInquiry);
                        this.update(inquiry);
                    } else {
                        this.save(inquiry);
                    }
                    saveOrUpdateToSnail(inquiry);
                }

//                truckInquiryMapper.batchSave(inquiries);
                result = RequestUtils.success("");
            } catch (Exception e) {
                e.printStackTrace();
                result = RequestUtils.failure("保存失败!" + e.getMessage());
            }
        } else {
            result = RequestUtils.success(null, "没有获取到求购信息!");
        }
        return result;
    }

    private TruckInquiry copyProperties(TruckInquiry source,TruckInquiry target){
        source.setHasSave(target.getHasSave());
        source.setTruckBuyId(target.getTruckBuyId());
        source.setCreatetime(target.getCreatetime());
        source.setSource(target.getSource());
        BeanUtils.copyProperties(source,target);
        return target;
    }

    /**
     * 处理老数据
     *
     * @return
     */
    public JSONObject dealOldData() {
        return getInquiryTruckFromOuman(1);
    }

    /**
     * 从欧曼获取的json数据转换位对象
     *
     * @param json
     * @return
     */
    private TruckInquiry dealJSONObject(JSONObject json) {

        String reqid = json.getString("reqid");
        String contactaddress = json.getString("contactaddress");
        String modelname = json.getString("modelname");
        String brandname = json.getString("brandname");
        String areaname = json.getString("areaname");
        String maxmileage = json.getString("maxmileage");
        String validatelimit = json.getString("validatelimit");
        String usedlimit = json.getString("usedlimit");
        String maxprice = json.getString("maxprice");
        String cartype = json.getString("cartype");
        String minmileage = json.getString("minmileage");
        String contacttel = json.getString("contacttel");
        String title = json.getString("title");
        String provincename = json.getString("provincename");
        String contactname = json.getString("contactname");
        String minprice = json.getString("minprice");
        String cityname = json.getString("cityname");
        String demand = json.getString("demand");

        TruckInquiry inquiry = new TruckInquiry();
        inquiry.setTruckId(reqid);
        inquiry.setAreaname(areaname);
        inquiry.setProvinceName(provincename);
        inquiry.setCityName(cityname);
        inquiry.setModelName(modelname);
        inquiry.setBrandName(brandname);
        inquiry.setMaxMileage(StringUtils.isEmpty(maxmileage) ? null : Float.valueOf(maxmileage));
        inquiry.setMinMileage(StringUtils.isEmpty(minmileage) ? null : Float.valueOf(minmileage));
        inquiry.setMaxPrice(StringUtils.isEmpty(maxprice) ? null : Float.valueOf(maxprice));
        inquiry.setMinPrice(StringUtils.isEmpty(minprice) ? null : Float.valueOf(minprice));
        inquiry.setValidateLimit(validatelimit);
        inquiry.setUsedLimit(StringUtils.isEmpty(usedlimit) ? null : Long.valueOf(usedlimit));
        inquiry.setCarType(cartype);
        inquiry.setContacttel(contacttel);
        inquiry.setContactname(contactname);
        inquiry.setContactAddress(contactaddress);
        inquiry.setTitle(title);
        inquiry.setDemand(demand);
        return inquiry;
    }

    /**
     * 将欧曼求购信息转换为蜗牛求购信息
     *
     * @param inquiry
     * @return
     */
    private PurchaseTruck convertTruckInquiryToPurchaseTruck(TruckInquiry inquiry) {
        PurchaseTruck purchaseTruck = new PurchaseTruck();

        purchaseTruck.setPlatform(EnumPlatform.DATA_OUMAN.getCode());
        purchaseTruck.setTitle(inquiry.getTitle());
        purchaseTruck.setLowprice(inquiry.getMinPrice());
        purchaseTruck.setHighprice(inquiry.getMaxPrice());
        purchaseTruck.setContactname(inquiry.getContactname());
        purchaseTruck.setContacttel(inquiry.getContacttel());
        purchaseTruck.setAddress(inquiry.getContactAddress());
        purchaseTruck.setCreatetime(new Date());
        purchaseTruck.setDeltag("0");
        purchaseTruck.setDescp(inquiry.getDemand());
        purchaseTruck.setExpirydate(DateUtil.defaultFormatStringToDate(inquiry.getValidateLimit()));
        purchaseTruck.setCarCount(1);
        String provinceName = inquiry.getProvinceName();
        String cityName = inquiry.getCityName();
        String areaname = inquiry.getAreaname();
        String modelName = inquiry.getModelName();
        String brandName = inquiry.getBrandName();
        ShtProvince shtProvince = areaService.getProvinceByname(provinceName);
        ShtCity shtCity = areaService.getShtCityByname(cityName);
        ShtDistrict shtDistrict = areaService.getShtDistrictByname(areaname, shtCity.getId(),shtProvince.getId());
        List<TruckModel> models = modelMapper.getByName(modelName);
        List<TruckBrand> brands = brandMapper.getByName(brandName);
        purchaseTruck.setProvinces(shtProvince.getId());
        purchaseTruck.setCity(shtCity.getId());
        if(shtDistrict!=null){
            purchaseTruck.setAreaid(shtDistrict.getId());
        }
        if (models != null&&models.size()>0) {
            purchaseTruck.setModel(models.get(0).getId());
        }

        if (brands != null && brands.size() > 0) {
            purchaseTruck.setBrandid(brands.get(0).getId());
        }
        purchaseTruck.setStatus("0");
        purchaseTruck.setUserid(1L);

        return purchaseTruck;
    }

    /**
     * 保存到蜗牛数据库中
     *
     * @param inquiry
     */
    private void saveOrUpdateToSnail(TruckInquiry inquiry) {

        //蜗牛数据库中新增的数据ID
        Long increment = 0L;

        //已保存到蜗牛数据库中,更新蜗牛数据中相应的表信息,否则新增
        if (inquiry.getHasSave() == 1) {
            increment = inquiry.getTruckBuyId();
            PurchaseTruck purchaseTruck = purchaseTruckMapper.getSingle(increment);
            purchaseTruck.setPlatform(EnumPlatform.DATA_OUMAN.getCode());
            purchaseTruck.setTitle(inquiry.getTitle());
            purchaseTruck.setLowprice(inquiry.getMinPrice());
            purchaseTruck.setHighprice(inquiry.getMaxPrice());
            purchaseTruck.setContactname(inquiry.getContactname());
            purchaseTruck.setContacttel(inquiry.getContacttel());
            purchaseTruck.setAddress(inquiry.getContactAddress());
            purchaseTruck.setCreatetime(new Date());
            purchaseTruck.setDeltag("0");
            purchaseTruck.setDescp(inquiry.getDemand());
            purchaseTruck.setExpirydate(DateUtil.defaultFormatStringToDate(inquiry.getValidateLimit()));
            purchaseTruck.setCarCount(1);
            String provinceName = inquiry.getProvinceName();
            String cityName = inquiry.getCityName();
            String areaname = inquiry.getAreaname();
            String modelName = inquiry.getModelName();
            String brandName = inquiry.getBrandName();
            ShtProvince shtProvince = areaService.getProvinceByname(provinceName);
            ShtCity shtCity = areaService.getShtCityByname(cityName);
            ShtDistrict shtDistrict = areaService.getShtDistrictByname(areaname, shtCity.getId(),shtProvince.getId());
            List<TruckModel> models = modelMapper.getByName(modelName);
            List<TruckBrand> brands = brandMapper.getByName(brandName);
            purchaseTruck.setProvinces(shtProvince.getId());
            purchaseTruck.setCity(shtCity.getId());
            purchaseTruck.setAreaid(shtDistrict.getId());
            if (models != null&&models.size()>0) {
                purchaseTruck.setModel(models.get(0).getId());
            }

            if (brands != null && brands.size() > 0) {
                purchaseTruck.setBrandid(brands.get(0).getId());
            }
            purchaseTruck.setStatus("0");
            purchaseTruckMapper.update(purchaseTruck);
        } else if (inquiry.getHasSave() == 0) {
            PurchaseTruck purchaseTruck = convertTruckInquiryToPurchaseTruck(inquiry);
            purchaseTruckMapper.save(purchaseTruck);
            inquiry.setTruckBuyId(purchaseTruck.getId());
            inquiry.setHasSave(HAS_SAVE);
            inquiry.setUpdatetime(new Date());
            truckInquiryMapper.update(inquiry);
        }


    }

}
